// pages/place-an-order/place-an-order.js
const App = getApp();
const SERVICE = require("../../service.js");

Page({

  /**
   * 页面的初始数据
   * 
   * @Data: SwiperCurrent => swiper的显示项（swiper-item）
   * @Data: filtrateItem => 筛选的显示项(0: 销量, 1: 价格, 2: 筛选 )
   * @Data: orderListData => 数据
   * @Data: goodstype_id => 商品分类ID
   * @Data: pages => 页数
   * @Data: totalPage => 总页数
   * @Data: sort => 排序方式
   * 
   */
  data: {
    SwiperCurrent:0,
    totalPage:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 商品分类列表
    let _this = this,
    td = this.data; 
    let openid = wx.getStorageSync("token");       
    _this.setData({
      page:1,
      sort:"sales_volume",
      showLoading:false,
      isNoData:true,
      filtrateItem:0,
      ordersId: App.globalData.ordersId,
      searchValue: App.globalData.search ? App.globalData.search : "",
      offer: "",
      price_min:"",
      price_max:"",   
      order:"DESC" 
    });
    
    wx.showNavigationBarLoading();    
    SERVICE.getGoodsSort({
      id: td.ordersId,
        sort: td.sort, 
        page: td.page,
        order:td.order,
        keyword: td.searchValue,
        offer: td.offer
        },(resStatus, data) => {
          console.log(data);
          wx.hideNavigationBarLoading();  
          App.globalData.ordersId = "";
          App.globalData.search = "";    
          if (resStatus) {
            _this.setData({
              orderListData: data.list,
              goodstype_id: td.ordersId,
              totalPage: data.totalPage
            });
            console.log("搜索:", td.ordersId);
           
          }else{
            _this.setData({
              orderListData: null
            });
          }
    });

    // 右侧分类筛选菜单
    SERVICE.getFilterMenu({}, (resStatus, data) => {
      if (resStatus) {
        for (var i in data) {
          data[i].selected = true;
        }
        _this.setData({
          filterMenuData: data
        });
      }
    });

    // 获取推荐价格区间
    SERVICE.getFilterRecommend({},(resStatus,data)=>{
      console.log("获取推荐价格区间:",data);
      if(resStatus){
        _this.setData({
          SectionData:data.data
        });
        console.log(_this.data.SectionData);
      }
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 
   * 方法
   * 
   * @Method: menu 搜索框的菜单按钮
   * @Method: SwiperScrollChange swiper的项(change事件)
   * @Method: ScrrenMenuConfirm (scrren-menu) 筛选菜单项的确认事件
   * @Method: SwiperScrollClower 触底事件
   */ 

  menu(e){
    let status = e.detail.status;
    this.setData({
      SwiperCurrent: status ? 1 : 0,
      filtrateItem: 0
    });
  },
  SwiperScrollChange(e){
    let Current = e.detail.current;
    this.setData({
      SwiperCurrent: Current,
      filtrateItem:0
    });
  },
  filtrate(e){
    let _this = this,
    td = this.data,
    filtrateItem = e.detail.item,
    price_filter = e.detail.priceFilter;    //选中默认为true（true为升价）
    this.setData({
      filtrateItem
    });

    // 筛选
    if (filtrateItem == 0){
      if (td.price_min || td.price_max) {
        td.sort = "sort_order";
      }else{
        td.sort = "sales_volume";        
      }
      td.page = 1,td.order = "DESC";
      wx.showLoading({
        title: "加载中...",
      });
      SERVICE.getGoodsSort({
        id: td.goodstype_id,
        sort: td.sort,
        page: td.page,
        order: td.order,
        price_min: td.price_min,
        price_max: td.price_max,
        keyword:td.searchValue,
        offer: td.offer
      }, (status, data) => {
        wx.hideLoading();
        if(status){
          _this.setData({
            orderListData: data.list,
            typeFilterSelected: null,
            itemFilterSelected: null,
            showLoading: false
          });
        }
      });
    } else if (filtrateItem == 1){
      td.sort = 'shop_price', td.page = 1;
      td.order = "DESC";
      console.log(td.goodstype_id);
      if (price_filter == true) {
        console.log("价格上升");
        wx.showLoading({
          title: "加载中...",
        });
        SERVICE.getGoodsSort({
          id: td.goodstype_id,
          sort: 'shop_price',
          order: td.order,
          price_min: '0',
          price_min: td.price_min,
          price_max: td.price_max,
          page: td.page,
          keyword: td.searchValue,
          offer: td.offer
        }, (status, data) => {
          wx.hideLoading();
          if(status){
            _this.setData({
              orderListData: data.list,
              typeFilterSelected: null,
              itemFilterSelected: null,
              showLoading: false
            });
          }
        });
      } else if (price_filter == false) {
        td.order = "ASC";
        wx.showLoading({
          title: "加载中...",
        });
        SERVICE.getGoodsSort({
          id: td.goodstype_id,
          sort: td.sort,
          order: td.order,
          price_max: 0,
          price_min: td.price_min,
          price_max: td.price_max,
          page: td.page,
          keyword: td.searchValue
        }, (status, data) => {
          wx.hideLoading();
            if(status){
              _this.setData({
                orderListData: data.list,
                typeFilterSelected: null,
                itemFilterSelected: null,
                showLoading: false
              });
            }
        });
      }
    } 
  },
  ScrrenMenuConfirm(e){
    let _this = this,
    td = this.data,
    price_min = parseFloat(e.detail.inputValue1) || "",
    price_max = parseFloat(e.detail.inputValue2) || "",
    offer = e.detail.offer || "",
    id = e.detail.itemId || "";
    App.globalData.ordersId = "";
    App.globalData.search = "";
    td.page = 1;
    wx.showNavigationBarLoading();
    if (price_min || price_max){
      td.sort = "sort_order";
    }
    SERVICE.getGoodsSort({
      id: id,
      sort: td.sort,
      order: td.order,
      page: td.page,
      keyword: td.searchValue,      
      price_min: price_min,
      price_max: price_max,
      offer:offer
    }, (resStatus, data) => {
      console.log(data);
      wx.hideNavigationBarLoading();
     
      if (resStatus) {
        _this.setData({
          orderListData: data.list,
          goodstype_id:id,
          price_min,
          price_max,
          totalPage: data.totalPage,
          filtrateItem:0
        });
      } else {
        _this.setData({
          orderListData: null,
          filtrateItem: 0          
        });
      }
    });
   
  },
  addCart(e){
    let _this = this,
    id = e.detail.id,
    itemData = e.detail.data,
    goods_id = itemData.goods_id;
    wx.showLoading({
      title: "加载中...",
    });
    // 获取规格
    SERVICE.getSpec({id},(resStatus,data)=>{
      wx.hideLoading();
      if (resStatus){
        _this.setData({
          showSpec: data.list,
          showSpecData: data,
          specNum: 1,
          showSpceItem: 0,
          goods_id
        });
      }else{
        console.log("yes");
        _this.setData({
          showGoodsNum:true,
          goodsNum:1,
          goodsNumData: itemData,
          goods_id
        });
      }
    });
  },
  
  specSubmit(e) {
    let _this = this,
    td = _this.data,
    num = e.detail.num, 
    spceId = e.detail.specId;
    let openid = wx.getStorageSync("token");         
    // 确定加入购物车（规格商品）
    SERVICE.addCart({
      goods_id: td.goods_id,
      number: num,
      spec: spceId,
      openid
    },(resStatus,data)=>{
       if(resStatus){
         _this.setData({
           showSpec: false,
           showGoodsNum: false
         });
         wx.showToast({
           title: "加入购物车成功！",
           duration: 1000,
           icon: "none",
           mask: true
         });
         setTimeout(() => {
           // 调用配件商品（有则显示，无则不显示）
           getGoodsMountings(_this, { id: td.goods_id});
         }, 1100);

       }else{
         wx.showToast({
           title: data.message,
           icon:"none",
           duration: 1000,
           mask: true
         });
       }
    });
  },
  submitRecommendGoods(e) {
    let _this = this, formData = e.detail.formData;
    let openid = wx.getStorageSync("token");   
    if (formData.length > 0){
      SERVICE.MultipleItemsAddCart({ 
        goods:JSON.stringify(formData),openid},
        (resStatus, data) => {
          console.log("配菜商品：",data);
          if (resStatus) {
            _this.setData({
              showRecommendGoods: false
            });
            wx.showToast({
              title: data.message,
              duration: 1000,
              mask: true
            });
          }
      });
    } else{
      wx.showToast({
        title: "请选择配菜",
        icon:"none",
        mask:true
      });
    }
  },
  SwiperScrollClower(){
    let _this = this,td = this.data;
    _this.setData({
      showLoading:true,
      isNoData:true
    });
    console.log("上拉加载更多...", td.totalPage);
    if ((td.page + 1) <= td.totalPage ){
        setTimeout(()=>{
          SERVICE.getGoodsSort({
            id: td.ordersId,
            sort: td.sort,
            page: ++td.page,
            order: td.order,
            keyword: td.searchValue
          },
            (resStatus, data) => {
              console.log(data);
              if (resStatus) {
                _this.setData({
                  orderListData: td.orderListData.concat(data.list),
                  goodstype_id: td.ordersId,
                  showLoading: false
                });
              }
            });
        },1000);
      }else{
      _this.setData({
        isNoData:false
      });
      }
  },
  search(e){
    console.log("搜索数据",e.detail.val);
    if(e.detail.val){
      App.globalData.search = e.detail.val;
      this.onShow();
    }else{
      App.globalData.search = null;
      this.onShow();
    }
  },
  input(e){
    this.setData({
      searchValue:e.detail.val
    });
    if (e.detail.val.length == 0){
      this.onShow();
    }
  }
});

/**
 * 商品配件
 * @param { String } id 商品id
 * @param { String } e this对象
 */
function getGoodsMountings(e,params) {
  SERVICE.getGoodsMountings(params,(resStatus,data)=>{
    if(resStatus){
      for (let i = 0; i < data.length; i++) {
        data[i].number = 1;
        data[i].checked = false;
      }
      e.setData({
        showRecommendGoods: true,
        recommendGoodsData: data
      });
    }
  });
}
